package com.jeff.game.tools.level;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Factory to construct a background image from a block file and block mapping
 */
public class BackgroundFactory
{
  /**
   * Builds the background image
   * @param width Resulting image width
   * @param height Resulting image height
   * @param blockFile Block file
   * @param map Block map
   * @return Full background image
   * @throws IOException
   */
  public BufferedImage build(
      int width, int height, BlockFile blockFile, BlockMap map)
      throws IOException
  {
    char[][] blocks = blockFile.toBlocks();
    return compose(width, height, blocks, map);
  }

  private BufferedImage compose(
      int width, int height, char[][] blocks, BlockMap map)
  {
    BufferedImage image = new BufferedImage(
        width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();

    int[] blockDims = new int[] {
        width / blocks[0].length, height / blocks.length };

    for (int i = 0; i < blocks.length; ++i)
    {
      for (int j = 0; j < blocks[i].length; ++j)
      {
        Image subimage = map.getImage(blocks[i][j]);
        graphics.drawImage(
            subimage, j * blockDims[0], i * blockDims[1], blockDims[0],
            blockDims[1], null);
      }
    }

    return image;
  }
}
